package com.parse;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.parse.entity.Entity;
import com.parse.util.ExcelUtil;
import com.parse.util.FileUtil;
import com.parse.util.StringUtils;

public class Main {
	public static String destFile;
	public static String tempFile;
	public static String key;
	public static String[] cols;

	private static Properties loadProperty() {
		Properties prop = new Properties();
		try {
			InputStream is = Main.class.getResourceAsStream("/config.properties");
			InputStreamReader io = new InputStreamReader(is, "UTF-8");
			prop.load(io);
			is.close();
			io.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return prop;
	}

	static {
		Properties prop = loadProperty();
		destFile = StringUtils.trim(prop.getProperty("destFile"));
		tempFile = StringUtils.trim(prop.getProperty("tempFile"));
		key = StringUtils.trim(prop.getProperty("key"));
		String[] tempCols = prop.getProperty("cols").replace(",", ",").replace("，", ",").split(",");
		cols = new String[tempCols.length + 1];
		cols[0] = key;
		System.arraycopy(tempCols, 0, cols, 1, cols.length - 1);
	}

	/**
	 * 源文件备份
	 */
	public static void step1(){
		SimpleDateFormat sd = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
		String str = sd.format(Calendar.getInstance().getTime());
		
		FileUtil.copyFile(destFile, destFile+str+".bak");
		FileUtil.copyFile(tempFile, tempFile+str+".bak");
		System.out.println(destFile + " " + tempFile);
		System.out.println("备份完成。");
	}
	
	/**
	 * 将临时文件的每行，根据配置的列
	 * 解析成一个{@Entity}
	 * 
	 * 所有的{@Entity} 都放到一个Map里边， key是根据配置找到的key
	 * value是整个Entity的值。
	 * @return
	 */
	public static Map<String, Entity> step2() {
		List<List<Object>> list = ExcelUtil.changeExcelToList(tempFile, 1);
		int[] index = new int[cols.length];
		for (int i = 0; i < index.length; i++) {
			index[i] = -1;
		}
		List<Object> firstRow = list.get(0);
		for (int i = 0; i < cols.length; i++) {
			index[i] = firstRow.indexOf(cols[i]);
		}

		Map<String, Entity> map = new HashMap<>();
		for (int i = 1; i < list.size(); i++) {
			Entity entity = new Entity();
			List<Object> temp = list.get(i);
			List<String> entityList = new ArrayList<>();
			String key = "";
			for (int j = 0; j < index.length; j++) {
				if (j == 0) {
					key = (String) temp.get(index[j]);
				} else {
					entityList.add((String) temp.get(index[j]));
				}
			}
			entity.setKey(key);
			entity.setCols(entityList);
			map.put(key, entity);
		}
		return map;
	}

	/**
	 * 根据配置项，得到要更新的是每一行的哪一列。 保存到index数组中。（Index数组第一个是key的位置）
	 * 然后遍历每一行，根据index记录的对应的要修改的位置，把Entity里边保存的对应的值设置到这个单元格。
	 * @param map
	 */
	public static void step3(Map<String, Entity> map) {
		File dest = new File(destFile);
		Workbook wb = null;
		Sheet sheet = null;

		boolean isXlsx = dest.getAbsolutePath().endsWith("xlsx");
		try {
			if (isXlsx) {
				wb = new XSSFWorkbook(new FileInputStream(dest));
			} else {
				wb = new HSSFWorkbook(new FileInputStream(dest));
			}

			sheet = wb.getSheetAt(0);
			Row row1 = sheet.getRow(0);

			int[] index = new int[cols.length];
			for (int i = 0; i < index.length; i++) {
				index[i] = -1;
			}

			List<String> firstRow = new ArrayList<>();
			for (int i = 0; i < row1.getLastCellNum(); i++) {
				Cell cell = row1.getCell(i);
				firstRow.add(cell.getStringCellValue());
			}

			for (int i = 0; i < cols.length; i++) {
				index[i] = firstRow.indexOf(cols[i]);
			}

			//
			for (int i = 1; i < sheet.getLastRowNum(); i++) {
				Row row = sheet.getRow(i);
				String key = row.getCell(index[0]).getStringCellValue();

				if (!map.containsKey(key)) {
					continue;
				}

				List<Object> logs = new ArrayList<>();
				logs.add(key);
				boolean isChange = false;

				List<String> destValues = map.get(key).getCols();
				int start = 0;
				for (int j = 1; j < index.length; j++) {
					Cell cell = row.getCell(index[j]);

					//保存日志，显示到
					try {
						switch (cell.getCellType()) {
						case Cell.CELL_TYPE_STRING:
							logs.add(cell.getStringCellValue());
							break;
						case Cell.CELL_TYPE_NUMERIC:
							logs.add(cell.getNumericCellValue());
							break;
						default:
							logs.add(cell);
							break;
						}
					} catch (Exception e) {

					}

					if (!StringUtils.isBlank(destValues.get(start))) {
						isChange = true;
						cell.setCellValue(destValues.get(start));
						start++;
					} else {
						start++;
						continue;
					}
				}
				
				if(isChange){
					System.out.println("原来的值：" + logs + " 行数：" + row.getRowNum());
					System.out.println("改变后值：" + map.get(key));
					System.out.println("------------------------------");
				}

			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		// 输出Excel文件
		FileOutputStream output;
		try {
			output = new FileOutputStream(dest);
			wb.write(output);
			output.flush();
			wb.close();
			System.out.println("Done.");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static void build(){
		step1();
		step3(step2());
	}
}
